<template>
  <div ref="echartDom"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose} from 'vue'
import {pxToRem} from "@/utils/index";

const props = defineProps({
  pieData: {
    type: Array,
    default: () => ([])
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b} : {c} ({d}%)'
      },
      series: [
        {
          type: 'pie',
          radius: [50 * props?.dialogData?.fontSizeTimes, 130 * props?.dialogData?.fontSizeTimes],
          center: ['50%', '50%'],
          roseType: 'area',
          label: {
            color: 'white',
            fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes)
          },
          emphasis: {
            label: {
              show: true,
              formatter: "{b|{b}}",
              borderColor: 'transparent',
              rich: {
                b: {
                  fontSize: pxToRem(18 * props?.dialogData?.fontSizeTimes),
                }
              }
            }
          },
          data: props?.pieData?.seriesData
        }
      ]
    }
    option && myChart.value.setOption(option, true);
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  initEchart();
};

defineExpose({
  updateChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h388 {
  height: 388px;
}
.dialog-h388 {
  width: 928px;
  height: 600px;
}
</style>